package com.youpai.platform.vulture.service.handler.detection;

import com.youpai.platform.vulture.common.entity.AccessMessage;
import com.youpai.platform.vulture.service.channel.VultureChannel;
import com.youpai.platform.vulture.service.constant.BizConstants;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import java.util.concurrent.TimeUnit;

/**
 * 心跳处理
 *
 * @date: 2023/2/24 13:59
 * @author: Welles
 * @version: 1.0
 */
public class HeartbeatCheckHandler implements TimerTask {

    private VultureChannel vultureChannel;

    public HeartbeatCheckHandler(VultureChannel vultureChannel) {
        this.vultureChannel = vultureChannel;
    }

    @Override
    public void run(Timeout timeout) throws Exception {
        if (null == vultureChannel || !vultureChannel.isActive()) {
            return;
        }
        if (BizConstants.HEARTBEAT_TIME_OUT > 0) {
            // 如果心跳超时，断开连接
            long lastReceiveHeartbeatTime = vultureChannel.getLastReceiveHeartbeatTime();
            if (System.currentTimeMillis() - lastReceiveHeartbeatTime > BizConstants.UN_HAND_SHARK_CONNECTION_TIME_OUT) {
                vultureChannel.getChannel().disconnect();
                vultureChannel = null;
            }
            return;
        }
        timeout.timer().newTimeout(timeout.task(), BizConstants.HEARTBEAT_INTERVAL, TimeUnit.MILLISECONDS);
        vultureChannel.send(AccessMessage.buildPingMessage());
    }
}
